<template>
	<!-- 系统目录 西药目录 -->
	<div class="box" id="rightCont">
		<!-- main -->
		<div class="main" id="main">
			<!-- left -->

			<!-- right -->
			<div class="main-right">
				<div class="main-icon">
					<div class="header-icon">
						<i class="el-icon-lcks"
							style="border-radius: 50%;font-size: 20px;padding: 6px;margin-left: 8px;;background-color: #409EFF;color: #fff;"></i>
						<span style="font-weight:300;margin-left: 12px;">科室档案</span>
					</div>
					<!-- btn2 -->
					<div class="main-icon-c">
						<span style="font-size: 12px;color: #606266;font-weight: bold;display: inline-block;width: 68px;">关键字：</span>
						<el-autocomplete  popper-class="my-autocomplete" v-model="searchValue" :fetch-suggestions="querySearch" placeholder="编码、名称"
						  size='mini' @select="handleSelect">
						  <i class="el-icon-Ssearch" slot="suffix" style="cursor: pointer;margin-right: 8px;" @click="handleIconClick"></i>
						  <template slot-scope="{ item }">
							<div class="name" style="font-size: 12px;">{{ item.supplierName }}</div>
						  </template>
						</el-autocomplete>
					</div>
					<!-- btn3 -->
					<div class="main-icon-c">
						<el-button v-for="(v,i) in headerBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini" @click="handClick(i)">{{ v.title }}</el-button>
					</div>
				</div>
				<!-- table -->
				<div class="table">
					<el-table :data="tableData" border @row-dblclick="handledbRow" :max-height="tableHeight"
					  element-loading-text="数据加载中..." v-loading="loading" element-loading-spinner="el-icon-refresh"
					  highlight-current-row @current-change="handleCurrentTableChange">
					  <el-table-column fixed="left" label="行号" type="index" width="50" align="center"></el-table-column> 
					  <el-table-column v-for="(col, inx) in tableRows" 
					    :key="inx" 
					    :prop="col.prop" 
					    :label="col.name" 
						:header-cell-style="{ background: '#f4f4f4 !important', border: '1px solid #ebeef5' }"
						:cell-style="{ border: '1px solid #ebeef5' }"
					    :formatter="col.formatter">
					  </el-table-column>
					</el-table>
					<!-- 分页 -->
					<el-pagination
					style="margin: 12px;"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="pageNum"
					:page-sizes="[20, 50, 100]"
					:page-size="pageSize"
					:total="totalSize"
					layout="total, sizes, prev, pager, next, jumper"
					background
					>
					</el-pagination>
				</div>
				<!-- feet -->
				<div class="feet" id="feet">
					<el-button v-for="(v,i) in feetBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini" @click="feetHandClick(v,i)">{{ v.title }}</el-button>
				</div>
			</div>
		</div>
		<!-- Model -->
		<div class="model">
			<!-- 新增 v-if="showChild" @close="showChild = false" -->
			<div class="addModel">
				<!-- <addModel ref="addModel" :parent-method="loadData" @success="handleSuccess"></addModel> -->
				<supplier-add-dialog ref="addDialog" @success="handleSuccess" />
			</div>
			<!-- 修改 -->
			<div class="editModel">
				
			</div>
			<!-- 查看 -->
			<div class="watchModel">
				
			</div>
		</div>

	</div>
</template>

<script>
	import SupplierAddDialog  from './dept/addDialogVisible.vue';
	// 接口
	// import { getDeptList, updateSupplierEntity }  from "@/api/supplier.js";
	
	import { getDeptList }  from "@/api/ks/ks.js";
	import { yglist } from "@/api/staff/staff.js"; // 获取员工信息
	
	export default {
		components: {
		    SupplierAddDialog
		},
		inject: ['reload'], // 无痕刷新
		data() {
			return {
				defaultProps: {
					children: 'children',
					label: 'label'
				},
				// str
				toCode:'',
				treeValue:'', 
				tableHeight:'570', // table的高度，以便超出高度显示滚动条
				currentHeight:'', // 用于计算table的高度，以便超出高度显示滚动条
				windowWidth: '', //表格自适应宽度
				searchValue:'',
				CatalogueName:'科室档案',
				DropDownedName:'',
				iconComes:'el-icon-xy',
				// boolean
				loading:false,
				disabled:true,
				// number
				ydNameId:0,
				pageNum: 1, //当前页currentPage
				pageSize: 20,
				totalSize: 20, //总条数
				pageSizeSave:0,
				// arr
				form: {},
				editform:{},
				res:[],
				NameOptions:[],
				restaurants: [], // 搜索关键字
				// title右侧按钮
				headerBtn:[
					{ title:"刷新", type:"primary", icon:"el-icon-refresh", loading:false}, { title:"高级", type:"", icon:"", loading:false},
				],
				// 页面默认按钮// 基础按钮配置（始终显示）
				defaultButtons:[
					// { title:"新增西成药",icon:"el-icon-adds", type:"primary" },
					{ title:"新增",icon:"el-icon-adds", type:"success" },
					{ title:"修改",icon:"el-icon-edit", type:"warning" },
					{ title:"查看",icon:"el-icon-watch", type:"primary" },
					// { title:"删除",icon:"el-icon-del", type:"danger" },
					// { title:"目录引用",icon:"el-icon-closeFiles", type:"primary" },
					{ title:"打印",icon:"el-icon-ggml", type:"primary" },
					{ title:"导出",icon:"el-icon-export", type:"primary" },
					{ title:"关闭",icon:"el-icon-close", type:"primary" },
				],
				// 最终使用的按钮数组
				feetBtn: [],
				// tableRows
				tableRows: [
				  { name: "科室编码", prop: "deptCode" },
				  { name: "科室名称", prop: "deptName" },
				  { name: "拼音简码", prop: "pyCode" },
				  { 
				    name: "医学类型", 
				    prop: "medicineType",
				    formatter: (row) => {
				      return this.medicineTypeMap[row.medicineType] || row.medicineType
				    }
				  },
				  { 
					name: "负责人", 
					prop: "personInCharge",
					formatter: (row) => {
					  return this.personInChargeMap[row.personInCharge] || row.personInCharge
					}
				  },
				  { name: "联系电话", prop: "personInChargeTel" },
				  { name: "物理位置", prop: "physicalPosition" },
				  { name: "操作时间", prop: "operatingTime" },
				  { name: "操作员", prop: "operatingUser" },
				  { name: "备注", prop: "remark" }
				],
				elTree:[
					{ label: '全部', path:'', title:'', icon:'el-icon-news',
						children:[
							{ id:1,label: '药库',path:'',title:'药库',icon:'el-icon-xy'},
							{ id:2,label: '物资',path:'',title:'物资',icon:'el-icon-zhongchengyao'},
							{ id:3,label: '设备',path:'',title:'设备',icon:'el-icon-zhongcaoyao'},
							{ id:4,label: '材料',path:'',title:'材料',icon:'el-icon-xyzp'},
							{ id:5,label: '固定资产',path:'',title:'固定资产',icon:'el-icon-xyjhtxyyzhy'},
						],
					},
				],
				tableData: [],
				currentTable: [],
				// props
				// 医学类型映射
				medicineTypeMap: {
				  1: '西药',
				  2: '中成药',
				  3: '中药',
				  4: '卫材',
				  5: '设备',
				  6: '材料',
				  7: '固定资产'
				},
				 // 负责人映射表
				personInChargeMap: {},
			};
		},
		mounted() {
			// 数据源
			this.loadData();
			//获取动态盒子宽度，实时赋值给右侧 =i> this.$refs.mainRight.offsetWidth;
			this.$nextTick(()=>{
				this.updateWindowWidth();
				window.addEventListener('resize', this.updateWindowWidth);
				this.currentHeight = this.$getHeights();
				this.getTableHeight();
				this.initButtons(); // 引入全局自定义封装方法
				this.chooseStaff();
			});
		},
		methods: {
			/*
				数据源
			*/
			 async loadData() {
			    let res = await getDeptList({
			      deptName: this.searchValue,
			      status: this.status,
			      pageNum: this.pageNum,
			      pageSize: this.pageSize
			    });
			
			if (res.code === 200) {
			  this.loading = true;
			  setTimeout(() => {
				this.loading = true; //开始加载
				this.tableData = res.data.content.map(item => {
				  // 确保status字段是字符串类型
				  item.status = item.status ? item.status.toString() : '1';
				  
				  // 添加负责人姓名
				  if (item.personInCharge && this.personInChargeMap[item.personInCharge]) {
					item.personInChargeName = this.personInChargeMap[item.personInCharge];
				  }
				  
				  return item;
				});
				
				this.totalSize = res.data.totalSize;
				this.loading = false;
				this.restaurants = this.tableData;
			  }, 888);
			}
			},
			initButtons() {
			    // 获取当前路由路径
			    const currentPath = this.$route.path;
			    // 获取路由对应的权限按钮
			    const routeButtons = this.$getRouteButtons(currentPath);
			    console.log(routeButtons,'routeButtonsrouteButtons');
			    // 合并到现有按钮数组
			    this.feetBtn = this.$mergeButtons(this.defaultButtons, routeButtons);
				// console.log(this.feetBtn,'this.feetBtnthis.feetBtn');
			},
			handleSuccess() {
			  // 新增成功后的回调，可以刷新列表等操作
			  this.fetchSupplierList();
			},
			async chooseStaff() {
			    // 员工信息数据源
			    let res = await yglist();
			    this.fzrOptions = res.data.map(v => {
			      return { label: v.fullName, value: v.id, ...v }
			    });
			    
			    // 构建负责人ID到姓名的映射表
			    this.personInChargeMap = {};
			    this.fzrOptions.forEach(item => {
			      this.personInChargeMap[item.id] = item.fullName;
			    });
			    
			    // 更新表格数据中的负责人名称
			    if (this.tableData && this.tableData.length > 0) {
			      this.tableData = this.tableData.map(item => {
			        if (item.personInCharge && this.personInChargeMap[item.personInCharge]) {
			          item.personInChargeName = this.personInChargeMap[item.personInCharge];
			        }
			        return item;
			      });
			    }
			},
			// 用于计算table的高度，以便超出高度显示滚动条
			getTableHeight(){
				let headerHeight = this.currentHeight.mainHeight
				let feetHeight = this.currentHeight.feetHeight
				let lastHeight = this.currentHeight.lastHeight
				this.tableHeight = this.currentHeight.rightContentHeight - feetHeight * 3
				// console.log(this.tableHeight,'this.tableHeightthis.tableHeight');
			},
			// 其他原有方法保持不变...
			querySearch(queryString, cb) {
				var restaurants = this.restaurants;
				var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
				clearTimeout(this.timeout);
				this.timeout = setTimeout(() => {
				  cb(results);
				}, 888 * Math.random());
			},
			// 状态切换方法
			async toggleStatus(row) {
			  try {
			    const newStatus = row.status === '1' ? '2' : '1';
			    const res = await updateSupplierEntity({
			      id: row.id,
			      status: newStatus
			    });
				if (res.code === 200) {
				  row.status = newStatus; // 更新本地状态
				  this.$message({
					type: 'success',
					message: `状态已${newStatus === '1' ? '启用' : '禁用'}`
				  });
				  this.loading = false;
				} else {
				  this.$message.error(res.message || '状态更新失败');
				  this.loading = false;
				} 
			  } catch (error) {
			    console.error('状态更新失败:', error);
			    this.$message.error('状态更新失败');
			  } finally {
			    this.loading = false;
			  }
			},
			createFilter(queryString) {
				return (restaurant) => {
				  return (restaurant.supplierName.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
				};
			},
			handleSelect(item) {
				this.searchValue = item.supplierName
				this.loadData();
			},
			handleIconClick(ev) {
				this.loadData();
			},
			handleNodeClick(data){
				this.treeValue = data.id;
				this.loadData();
			},
			handClickName(val){
				console.log(val);
			},
			async editFormValue(row){
				if(row){
					this.loading = true;
					setTimeout(()=>{
						let param = {
							id:row.id,
							label:'编辑',
							edit:true,
							isShow:true,
							system:true,
						}
						this.loading = false;
						this.$refs.addModel.open(param);
					},888)
				} else { 
					this.$message({ type: "info", message: "未知异常，请稍后重试！"});
				}
			},
			handleDelete(rowId){
				console.log(rowId);
				this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
				  confirmButtonText: '确定',
				  cancelButtonText: '取消',
				  type: 'warning'
				}).then(async() => {
					let ress = await deleteDrugP({
						drugId: rowId
					})
					if(ress.code === 200){
						this.$message({type:'success',message:'已删除'});
						this.loadData();
					}else{
						this.$message.error(ress.message)
					}
				}).catch(() => {
				  this.$message({
					type: 'info',
					message: '已取消删除'
				  });          
				});
			},
			saveEditData(){
				
			},
		    columnWidth(col, list) {
		         let prop = col.prop,lab = col.lab;
		         let width = 20;
		         let maxlenStr = "";
		         for (let info of list) {
		           if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
		         }
		         width = Math.max(width, len(lab), len(maxlenStr));
		         return width + 12;
		         function len(str) {
		           let length = 0;
		           for (const char of str + "") {
		             if ("a" <= char && char <= "z") length += 12;
		             else if ("A" <= char && char <= "Z") length += 12;
					 else if (Number.isFinite(Number(char))) length += 12;
		             else if (char >= "\u4e00" && char <= "\u9fa5") length += 32;
		             else length += 12;
		           }
		           return length;
		         }
		    },
			handClick(i) {
				switch (i) {
					case 0:
						this.loading = true;
						setTimeout(() => {
							this.reload();
							this.$message({type:'success',message:'已刷新'})
							this.loading = false;		
						}, 1500)
					break;
					case 1:
						this.$message({ type: "info", message: "暂不支持,请联系工作人员!"});
					break;
				}
			},
			feetHandClick(v){
				console.log(v);
				if(v.title == '新增' || v.title.includes('新增')){
					// 处理索引2的逻辑 => 新增 -> 调用子组件
					let param = {
						nameTitle:'新增科室'
					}
					this.$refs.addDialog.open(param);
				}
				// 处理逻辑 => 修改
				else if (v.title == '修改' || v.title.includes('修改')){
					// 处理索引1的逻辑 => 修改
					if(this.currentTable.length === 0){
						this.$message({ type: "warning", message: "请先选择一条要编辑的数据."});
					}else{
						this.loading = true;
						setTimeout(()=>{
							let param = {
								id:this.currentTable.id,
								nameTitle:'修改科室',
								isShow:true,
								system:true,
							}
							this.loading = false;
							this.$refs.addDialog.open(param);
						},888)
						
					}
				}
				// 处理逻辑 => 删除
				else if(v.title == '删除'){
					// 处理索引2的逻辑 => 删除
					if(this.currentTable.length != 0){
						this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
						  confirmButtonText: '确定',
						  cancelButtonText: '取消',
						  type: 'warning'
						}).then(async() => {
							let delId = this.currentTable[0].id;
							let res = await deldocMark({id:delId})
							if(res.code === 200){
								setTimeout(()=>{
									this.$message({ type: 'success', message: '已删除'})
									this.loadData();
								},1888)
							}else{
								this.$message({ type: 'error', message: 'fail！'})
							}
						}).catch(() => {
						  this.$message({
							type: 'info',
							message: '已取消删除'
						  });          
						});
					}else{
						this.$message({ type: 'warning', message: '请先选择一条要删除的数据'});
					}
				}
				// 处理逻辑 => 查看
				else if(v.title == '查看'){
					// 处理索引查看的逻辑 => 查看
					if(this.currentTable.length === 0){
						this.$message({ type: "warning", message: "请先选择一条要查看的数据."});
					}else{
						this.loading = true;
						setTimeout(()=>{
							let param = {
								id:this.currentTable.id,
								nameTitle:'查看',
								isShow:true,
								system:true,
							}
							this.loading = false;
							this.$refs.addDialog.open(param);
						},888)
					}
				}
				// 处理逻辑 => 打印
				else if(v.title === '打印'){
					this.handlePrint();
				}
				// 处理逻辑 => 导出
				else if(v.title === '导出'){
					this.$confirm('敬请期待')
					.then(_ => {})
					.catch(_ => {});
				}
				// 处理逻辑 => 关闭
				else{
					setTimeout(() =>{
						window.history.back();
					},888)
				}
			
			},
			handleCurrentTableChange(val){
				this.currentTable = val
			},
			handledbRow(row, column, event){
				if(row){
					this.loading = true;
					setTimeout(()=>{
						let param = {
							id:row.id,
							label:'查看',
							isShow:false,
							system:true,
						}
						this.loading = false;
						this.$refs.addModel.openAddModel(param);
					},888)
				} else { 
					this.$message({ type: "info", message: "未知异常，请稍后重试！"});
				}
			},
			handleClose(done) {
				this.$confirm('确认关闭？')
				  .then(_ => {
					this.formdisabled = true;
					location.reload();
					done();
				  })
				  .catch(_ => {
					this.formdisabled = this.formdisabled;
				  });
			},
			handleCommand(command) {
			  switch (command) {
				case 'a':
				  this.DropDownedName = '可用'
				  break;
				case 'b':
				  this.DropDownedName = '禁用'
				  break;
				case 'c':
				  this.DropDownedName = '全部'
				  break;
			  }
			},
			handleSizeChange(val) {
				this.pageNum = val;
				this.loadData();
			},
			handleCurrentChange(val) {
				this.pageNum = val;
				this.loadData();
			},
			updateWindowWidth() {
			    this.windowWidth = window.innerWidth - 288;
			},
		}
	}
</script>

<style lang="less" scoped>
	.box {
	  height: calc(100vh - 90px); // 减去导航栏高度
	  width: 100%;
	  overflow: hidden;
	
		/deep/ .el-table {
	    width: 100% !important;
	    
	    .el-table__body-wrapper {
	      overflow-x: auto !important;
	    }
	    
	    .el-table__header-wrapper {
	      overflow-x: hidden !important;
	    }
		/* 小眼睛图标样式 */
		.el-icon-watch {
		  color: #409EFF;
		  &:hover {
		    color: #66b1ff;
		  }
		}
		.el-icon-shield {
		  color: #F56C6C;
		  &:hover {
		    color: #f78989;
		  }
		}
	}
	/deep/ .el-switch__label *{
		font-size: 12px;
	}
	/deep/ .el-table .cell{
		font-size: 12px;
		text-overflow: ellipsis;
		white-space: nowrap;
		overflow: hidden;
	}
	/deep/ .el-table th{
		font-size: 12px;
		background-color: #f1f1f1;
		border: none;
		color: #2d2d2d;
	}
	/deep/ .el-table {
	    width: 100%;
	    // height: 100% !important;
	    .el-table__body-wrapper {
	      overflow-x: hidden;
	    }
	}
	/* 自定义高亮颜色 */
	::v-deep .el-table__body tr.current-row > td {
	  background-color: #00557f !important;
	  color: #f9f9f9; /* 可选：修改文字颜色 */
	}
	  .main {
	    display: flex;
	    height: 100%;
	    width: 100%;
	
	    // 左侧树形菜单
	    .main-left {
	      width: 128px;
	      height: 100%;
	      background: #f5f7fa;
	      border-right: 1px solid #e6e6e6;
	      overflow-y: auto;
	      scrollbar-width: none; /* Firefox */
	      -ms-overflow-style: none; /* IE 10+ */
	      
	      &::-webkit-scrollbar {
	        display: none; /* Chrome Safari */
	      }
	
	      /deep/ .el-tree {
	        height: 100%;
	        .el-tree-node__content {
	          height: 36px;
	        }
	      }
	    }
	    
	    // 右侧内容区域
	    .main-right {
	      flex: 1;
	      display: flex;
	      flex-direction: column;
	      height: 100%;
	      overflow: hidden;
	      
	      // 顶部搜索区域
		.main-icon {
			display: flex;
			align-items: center;
			padding: 12px;
			line-height: 40px;
			.main-icon-a{
				// width: 240px;
				// background-color: #00557f;
			}
			.main-icon-b{
				margin-left: 28px;
				/deep/ .el-dropdown{
					font-size: 12px;
					cursor: pointer;
				}
				/deep/ .el-dropdown:hover {
					font-weight: bold;
					color: #66b1ff;
				}
				/deep/ .el-icon--right{
					// background-color: #66b1ff;
				}
				/deep/ .el-popper[x-placement^=bottom]{
					margin-top: 0;
				}
			}
			// c
			.main-icon-c{
				display: flex;
				align-items: center;
				margin-left: 28px;
				/deep/ [data-v-2bacc09b] .el-color-picker__icon, .el-input[data-v-2bacc09b], .el-textarea[data-v-2bacc09b]{
					width: 80%;
				}
			}
		}
	      
	      // 表格容器（带滚动）
	      .table {
	        flex: 1;
			width: 100%;
	        overflow: hidden;
	        display: flex;
	        flex-direction: column;
			/deep/ .el-pagination {
				margin: 12px;
			}
	    }
	      
	      // 底部固定区域
	      .feet {
	        height: 40px;
	        display: flex;
			align-items: center;
	        padding: 12px;
	        background: #fff;
	        border-top: 1px solid #e6e6e6;
	        flex-shrink: 0;
	        
	        .feetBtn {
	          gap: 8px;
	        }
			
	        }
	    }
	  }
		
		.addModel{
			/deep/ .el-dialog__header{
				padding: 12px;
				line-height: 28px;
				background-color: #007bb0;
			}
			/deep/ .el-dialog__title{
				color: #fff;
				font-size: 12px;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close{
				color: #fff;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close:hover{
				background-color: brown;
			}
			/deep/ .el-form-item__label{
				font-size: 12px;
			}
		}
		.editModel{
			/deep/ .el-dialog__header{
				padding: 12px;
				line-height: 28px;
				background-color: #007bb0;
			}
			/deep/ .el-dialog__title{
				color: #fff;
				font-size: 12px;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close{
				color: #fff;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close:hover{
				background-color: brown;
			}
			/deep/ .el-form-item__label{
				font-size: 12px;
			}
		}
	}

</style>